<template>
  <div style="height: 40px">
    <table-header-bar
      :btn-list="allFuncBtnList"
      @btn-method="btnMethod"
    ></table-header-bar>
  </div>
  <base-table
    :table-data="tableData"
    :table-column-filed-list="props.filedPropertyList"
    :selects="currentSelects"
    :table-fixed-func-btn-list="tableFixedFuncBtnList"
    @sort-change="sortChange"
    @select-change="selectChange"
    @fixed-func-btn-method="fixedFuncBtnMethod"
  >
  </base-table>
  <submit-form-dialog
    v-model="submitFormVisible"
    :width="props.width"
    :title="props.submitFormTitle"
    :left-btn-area-visible="leftBtnAreaVisible"
    :previous-disabled="previousDisabled"
    :next-disabled="nextDisabled"
    @confirm="submit"
    @next-record="nextRecord"
    @previous-record="previousRecord"
    @close="changeSubmitFormVisible"
  >
    <template #dialog-content-slot>
      <base-form
        :key="Date.now()"
        v-model="submitForm"
        :form-filed-list="props.filedPropertyList"
        :submit-form-title="submitFormTitle"
        @success-validate="successValidate(submitForm)"
        @change-event="changeEvent"
        @select-focus-event="selectFocusEvent"
        ref="submitFormRef"
      ></base-form>
    </template>
  </submit-form-dialog>
  <import-form-dialog
    v-model="importFormVisible"
    :upload-url="props.urlList.modifyingBatchUrl"
    @get-record="refreshRecord"
    @submit-json-format="submitJsonFormat"
    @close="changeImportFormVisible"
  ></import-form-dialog>
  <advance-search-dialog
    v-model="advancedSearchVisible"
    :width="props.width"
    :advanced-search-form="advancedSearchForm"
    :advance-search-list="props.filedPropertyList"
    @close="changeAdvancedSearchVisible"
    @confirm="advanceSearchConfirm"
  ></advance-search-dialog>
</template>

<script lang="ts" setup>
import BaseTable from "@/components/table/base/BaseTable.vue";
import { onMounted, Ref, ref } from "vue";
import { Button, FixedFuncBtn, TableUrl } from "@/models/TableSetting";
import TableHeaderBar, {
  HeaderBtn,
} from "@/components/table/simple/TableHeaderBar.vue";
import DataOption from "@/components/table/simple/DataOption";
import SubmitFormDialog from "@/components/dialog/submit/SubmitFormDialog.vue";
import BaseForm from "@/components/form/basic/BaseForm.vue";
import api from "@/utils";
import AdvanceSearchDialog from "@/components/dialog/advanceSearch/AdvancedSearchDialog.vue";
import ImportFormDialog from "@/components/dialog/import/ImportFormDialog.vue";
import ImportFormDialogEvent from "@/components/dialog/import/ImportFormDialogEvent";
import Scope from "@/models/Scope";
import { BtnNameEnum } from "@/components/table/simple/BtnNameEnum";
import FormEvent from "@/components/table/simple/FormEvent";
import FiledProperty from "@/models/FiledProperty";
import { FormDialogVisible } from "@/components/table/simple/FormDialogVisible";
import { ElLoading } from "element-plus";
import { AdvancedSearchDialogEvent } from "@/components/dialog/advanceSearch/AdvancedSearchDialogEvent";
import { ElMessage } from "element-plus/es";

export interface SimpleTableProps {
  urlList: TableUrl;
  isEdit?: boolean; //表单是否有编辑按钮
  width?: string; //表单的宽度
  leftBtnAreaVisible?: boolean;
  submitFormTitle?: string; // 表单的标题
  filedPropertyList?: Array<FiledProperty>;
  currentUseBtnList?: Array<BtnNameEnum>; // 当前页面使用的功能按钮
  buttonList?: Array<Button>; // 当前页面中操作选项的其他操作
  tableName?: string; // 操作的表名，暂时用来控制下载批量导入模板的名字
}

onMounted(() => {
  // console.log("ws 执行前");
  // const ws = new WebSocket("ws://localhost:8080" + props.urlList.refreshUrl);
  // console.log("ws 之后的事件");
  // ws.onopen = () => {
  //   ws.send("111");
  //   console.log("连接服务端成功");
  // };
});

const props = withDefaults(defineProps<SimpleTableProps>(), {
  width: "50%",
  isEdit: true,
  leftBtnAreaVisible: true,
  urlList: () => {
    return {
      refreshUrl: "",
      modifyingSingleUrl: "",
      modifyingBatchUrl: "",
      deleteUrl: "",
    } as TableUrl;
  },
  filedPropertyList: () => {
    return [];
  },
  currentUseBtnList: () => {
    return [BtnNameEnum.ADD, BtnNameEnum.REFRESH, BtnNameEnum.DELETE];
  },
  buttonList: () => {
    return [] as Array<Button>;
  },
});

const emits = defineEmits<{
  (e: "different-operation", name: string, scope: Scope): void;
  (e: "change-event", val: string | unknown): void;
  (e: "select-focus-event"): void;
  (
    e: "reset-submit-form",
    submitForm: Ref,
    callback: (submitForm: Ref) => void
  ): void;
  (
    e: "reset-submit-data",
    submitData: Ref,
    callback: (resetFrom: Record<string, unknown>) => void
  ): void;
  (
    e: "reset-data-before-edit",
    editForm: Ref,
    callback: (resetEditFrom: Record<string, unknown>) => void
  ): void;
  (
    e: "before-show-table-data",
    TableData: Ref,
    callback: (resetTableData: Record<string, unknown>) => void
  ): void;
}>();

onMounted(() => {
  // const ws = new WebSocket("ws://localhost:8080" + props.urlList.refreshUrl);
  // ws.onmessage = (e: any) => {
  //   tableData.value = e;
  // };
});

// 当下拉选择框数据变化时向外抛出事件
const changeEvent = (val: string | unknown) => {
  emits("change-event", val);
};

const selectFocusEvent = () => {
  emits("select-focus-event");
};
const tableData = ref();

// 获取数据
const { data, getRecord } = DataOption();

// 刷新数据
const refreshRecord = async () => {
  ElLoading.service({ text: "加载中..." });
  await getRecord(props.urlList.refreshUrl).then(() => {
    tableData.value = data.value;
    emits(
      "before-show-table-data",
      tableData,
      (resetTableData: Record<string, unknown>) => {
        tableData.value = resetTableData;
      }
    );
    ElLoading.service().close();
  });
};

refreshRecord().then(() => {
  ElMessage.success({ message: "查询成功!" });
});

// 改变排序.
const sortChange = (data: []) => {
  tableData.value = data;
};

// 是否有勾选的数据.
const isSelected: Ref<boolean> = ref(true);

// 当前勾选的选项.
let currentSelects = [] as Array<Record<string, string>>;

// 改变选择项
const selectChange = (selects: []) => {
  currentSelects = selects;
  isSelected.value = selects.length === 0;
};

// 批量导入
const { importFormVisible, changeImportFormVisible, submitJsonFormat } =
  ImportFormDialogEvent(props);

// 申明新增/编辑表单.
const submitForm = ref();
// 表单的Ref.
const submitFormRef = ref();
// 新增、编辑表单窗口的标题.
const submitFormTitle = ref("");

// 上一条，下一条按钮显示与隐藏
const leftBtnAreaVisible = ref(false);
// 添加表单显示与隐藏
const { changeSubmitFormVisible, submitFormVisible } = FormDialogVisible();

// 组合搜索表单显示与隐藏
const { advancedSearchVisible, changeAdvancedSearchVisible } =
  AdvancedSearchDialogEvent();
// 记录上次组合搜索的条件
const advancedSearchForm = ref();
// 执行组合搜索
const advanceSearchConfirm = (searchForm: Ref<Record<string, unknown>>) => {
  getRecord(props.urlList.refreshUrl, searchForm.value).then(() => {
    advancedSearchForm.value = searchForm.value;
    tableData.value = data.value;
  });
};
// 按钮事件
const {
  clickAddBtn,
  clickEditBtn,
  clickDeleteBtn,
  clickInvalidBtn,
  sendDeleteRequest,
  sendInvalidRequest,
} = FormEvent();

const tableFixedFuncBtnList = {
  label: "操作",
  width: 250,
  funcBtnListVisible: true,
  buttonList: [
    {
      label: "编辑",
      name: "edit",
      icon: "edit",
    },
  ],
} as FixedFuncBtn;

// 添加操作中的其他操作
const initTableFixedFuncBtnList = () => {
  if (!props.isEdit) {
    tableFixedFuncBtnList.buttonList = [];
  }
  tableFixedFuncBtnList.buttonList = tableFixedFuncBtnList.buttonList.concat(
    props.buttonList
  );
};
initTableFixedFuncBtnList();

const fixedFuncBtnMethod = (scope: Scope, name: string) => {
  switch (name) {
    case "edit":
      changeSubmitFormVisible();
      leftBtnAreaVisible.value = props.leftBtnAreaVisible;
      clickEditBtn(scope, dataIndex, submitForm, submitFormTitle);
      emits(
        "reset-data-before-edit",
        submitForm,
        (resetEditFrom: Record<string, unknown>) => {
          submitForm.value = resetEditFrom;
        }
      );
      break;
    default:
      emits("different-operation", name, scope);
      break;
  }
};

//当前数据所在总数据的位置下标
const dataIndex = ref();
const previousDisabled = ref();
const nextDisabled = ref();

// 点击下一条数据的逻辑判断
const nextRecord = () => {
  if (dataIndex.value == tableData.value.length - 1) {
    nextDisabled.value = true;
  } else {
    dataIndex.value += 1;
    submitForm.value = JSON.parse(
      JSON.stringify(tableData.value[dataIndex.value])
    );
    previousDisabled.value = false;
    nextDisabled.value = false;
  }
};

// 点击上一条数据的逻辑判断
const previousRecord = () => {
  if (dataIndex.value == 0) {
    previousDisabled.value = true;
  } else {
    dataIndex.value -= 1;
    submitForm.value = JSON.parse(
      JSON.stringify(tableData.value[dataIndex.value])
    );
    previousDisabled.value = false;
    nextDisabled.value = false;
  }
};

// 批量引入
const clickBatchImportBtn = () => {
  changeImportFormVisible();
};

const clickResetBtn = () => {
  advancedSearchForm.value = {};
  getRecord(props.urlList.searchUrl, {}).then(() => {
    tableData.value = data.value;
  });
};
// 所有的功能按钮列表.
const allFuncBtnList = [
  {
    name: "新增",
    title: "add",
    visible: false,
    color: "#00cd00",
    icon: "circle-plus",
    disabled: ref(false),
  },
  {
    name: "刷新",
    title: "refresh",
    visible: false,
    color: "#409eff",
    icon: "refresh-right",
    disabled: ref(false),
  },
  {
    name: "删除",
    title: "delete",
    visible: false,
    color: "#b9c9c7",
    icon: "delete",
    disabled: isSelected,
  },
  {
    name: "批量导入",
    title: "batchImport",
    visible: false,
    color: "#9400D3",
    icon: "upload-filled",
    disabled: ref(false),
  },
  {
    name: "批量导入模板",
    title: "batchImportTemplate",
    visible: false,
    color: "#9370DB",
    icon: "download",
    disabled: ref(false),
  },
  {
    name: "批量作废",
    title: "batchInvalid",
    visible: false,
    color: "#ff4040",
    icon: "failed",
    disabled: isSelected,
  },
  {
    name: "组合搜索",
    title: "advancedSearch",
    visible: false,
    color: "#f7c900",
    icon: "search",
    disabled: ref(false),
  },
  {
    name: "重置搜索",
    title: "resetSearch",
    visible: false,
    color: "#000000",
    icon: "refresh",
    disabled: ref(false),
  },
] as HeaderBtn[];

// 按钮执行的事件
const btnMethod = async (btnTitle: string) => {
  switch (btnTitle) {
    case "add":
      leftBtnAreaVisible.value = false;
      changeSubmitFormVisible();
      clickAddBtn(submitForm, submitFormTitle, props.filedPropertyList);
      // 给表单的某些属性添加默认值（如果需要，由父组件实现）
      await emits(
        "reset-submit-form",
        submitForm,
        (callBackSubmitForm: Ref) => {
          submitForm.value = callBackSubmitForm.value;
        }
      );
      break;
    case "refresh":
      await refreshRecord();
      break;
    case "delete":
      clickDeleteBtn(currentSelects)
        .then(() => {
          sendDeleteRequest(currentSelects, props.urlList.deleteUrl)
            .then(() => {
              refreshRecord();
            })
            .catch((cancel) => {
              console.log(cancel);
            });
        })
        .catch((cancel) => {
          console.log(cancel);
        });
      break;
    case "batchImport":
      clickBatchImportBtn();
      break;
    case "batchImportTemplate":
      console.log("批量导入模板");
      console.log(props.tableName);

      // require("../../../assets/importTemplate/department.xlsx"),
      //服务器搭建后把模板放入服务器，配置访问路径映射
      // window.open(
      //   "https://cube.elemecdn.com/e/fd/" + props.tableName + ".xlsx",
      //   "_self"
      // );
      break;
    case "batchInvalid":
      // 先打开提示窗口, 然后执行作废或取消作废操作，最后刷新数据。
      clickInvalidBtn(currentSelects)
        .then(() => {
          sendInvalidRequest(currentSelects, props.urlList.invalidUrl)
            .then(() => {
              refreshRecord();
            })
            .catch((cancel) => {
              console.log(cancel);
            });
        })
        .catch((cancel) => {
          console.log(cancel);
        });
      break;
    case "advancedSearch":
      changeAdvancedSearchVisible();
      break;
    case "resetSearch":
      clickResetBtn();
      break;
  }
};

// 遍历传入的功能按钮将需要显示的按钮visible设置为true
const chooseButton = (currentUseBtnList: []) => {
  allFuncBtnList.forEach((item) => {
    if (currentUseBtnList.indexOf(item.title as never) > -1) {
      // 如果组合搜索按钮显示，则重置搜索按钮也显示
      if (item.title === "advancedSearch") {
        allFuncBtnList.forEach((item) => {
          if (item.title === "resetSearch") {
            item.visible = true;
          }
        });
      }
      item.visible = true;
    }
  });
};

chooseButton(props.currentUseBtnList as []);

const submitFormType = ref();
// 提交表单之前进行表单校验
const submit = async (type: string) => {
  submitFormType.value = type;
  await submitFormRef.value.validForm();
};

// 表单数据存储
const successValidate = async (form: Ref<Record<string, unknown>>) => {
  // 如果需要对提交表单数据进行修改等操作，交给父组件完成
  await emits(
    "reset-submit-data",
    form,
    (resetFrom: Record<string, unknown>) => {
      form.value = resetFrom;
      console.log(form);
    }
  );
  // 如果数据是修改 则更新修改人和修改时间，否则添加创建人和创建时间
  if (
    form["createUser"] !== undefined &&
    form["createUser"] !== "" &&
    form["createUser"] !== null
  ) {
    form["modifiedUser"] = sessionStorage.getItem("userName");
    form["modifiedGmt"] = new Date();
  } else {
    form["createGmt"] = new Date();
    form["createUser"] = sessionStorage.getItem("userName");
  }
  if (submitFormTitle.value == "新增") {
    api.http
      .postJson(props.urlList.modifyingSingleUrl, form)
      .then(() => {
        getRecord().then(() => {
          tableData.value = data.value;
        });
      })
      .catch((err) => {
        console.log(err);
      });
  } else if (submitFormTitle.value == "编辑") {
    api.http
      .putJson(props.urlList.modifyingSingleUrl + "/" + form["id"], form)
      .then((res) => {
        console.log(res);
        getRecord().then(() => {
          tableData.value = data.value;
        });
      })
      .catch((err) => {
        console.log(err);
      });
  }
  // 如果点击的按钮为 “确认并关闭” ，则关闭 SubmitForm表单
  if (submitFormType.value == "confirmAndClose") {
    changeSubmitFormVisible();
  }
  submitFormType.value = "";
};
</script>

<style scoped></style>
